package aplicacao.categoria;

import aplicacao.GuiResultadoBusca;
import aplicacao.interfaces.ResultadoBusca;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableCellRenderer;
import modelo.Categoria;
import modelo.excecoes.CategoriaDadoIncorretoException;
import modelo.excecoes.DAOException;

/**
 *
 * @author  Renato Pinheiro
 */
public class CRUDCategoria extends javax.swing.JDialog implements FocusListener,
        KeyListener, MouseListener, ResultadoBusca {

    /** Largura das colunas do jTable*/
    private final int[] larguraColunas = { 150, 130, 130, 130, 130};
    
    /** Flag do modo atual de operação
     1 - Inclusão, 2 - Alteração e 3 exclusão */
    private int modoAtual = 0;
    
    /** Creates new form CRUDCategoria */
    public CRUDCategoria(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        // Setando ouvintes da categoria
        jTableCategorias.addFocusListener(this);
        jTableCategorias.addMouseListener(this);
        jTableCategorias.addKeyListener(this);          

        try {
            // Ajusta o modelo do JTable
            jTableCategorias.setModel(new TableModelCategoria());
        } catch (CategoriaDadoIncorretoException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao recuperar os dados " +
                    "das categorias\n\n"+ex.getMessage(),
                    "Erro", JOptionPane.ERROR_MESSAGE);
            util.Util.gravaExcecao(ex, this);
            throw new RuntimeException();
        } catch (DAOException ex) {
            JOptionPane.showMessageDialog(this, "Problemas no acesso ao banco" +
                    " de dados", "Erro", JOptionPane.ERROR_MESSAGE);
            throw new RuntimeException("Erro no acesso ao banco de dados");
        }
        
        // Ajustando a aparência do jTable
        DefaultTableCellRenderer modeloCelulaAlinhamento = 
                new DefaultTableCellRenderer();
        
        // Alinhando a primeira e a terceira coluna para o centro
        modeloCelulaAlinhamento.setHorizontalAlignment(JLabel.CENTER);
        
        jTableCategorias.getColumnModel().getColumn(0).setCellRenderer(
                modeloCelulaAlinhamento);
        jTableCategorias.getColumnModel().getColumn(1).setCellRenderer(
                modeloCelulaAlinhamento);
        jTableCategorias.getColumnModel().getColumn(2).setCellRenderer(
                modeloCelulaAlinhamento);
        jTableCategorias.getColumnModel().getColumn(3).setCellRenderer(
                modeloCelulaAlinhamento);
        jTableCategorias.getColumnModel().getColumn(4).setCellRenderer(
                modeloCelulaAlinhamento);        

        // Centralizando
        this.setLocationRelativeTo(null);
        
        // Ajustando o tamanho
        this.setSize(600, 350); // 588, 324
        
        // Exibindo
        this.setVisible(true);
      
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane = new javax.swing.JScrollPane();
        jTableCategorias = new javax.swing.JTable();
        btnConfirmar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jtfNome = new javax.swing.JTextField();
        jtfNumRounds = new javax.swing.JTextField();
        cmbSexo = new javax.swing.JComboBox();
        jpPeso = new javax.swing.JPanel();
        jtfPesoMinimo = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jtfPesoMaximo = new javax.swing.JTextField();
        jpIdade = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jtfIdadeMinima = new javax.swing.JTextField();
        jtfIdadeMaxima = new javax.swing.JTextField();
        jpGraduacao = new javax.swing.JPanel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jtfGraduacaoMinima = new javax.swing.JTextField();
        cmbGubMinimo = new javax.swing.JComboBox();
        jtfGraduacaoMaxima = new javax.swing.JTextField();
        cmbGubMaximo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jmbCategorias1 = new javax.swing.JMenuBar();
        jmIncluir = new javax.swing.JMenu();
        jmAlterar = new javax.swing.JMenu();
        jmExcluir = new javax.swing.JMenu();
        jmProcurar = new javax.swing.JMenu();
        jmSair = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Dados das categorias");

        jTableCategorias.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane.setViewportView(jTableCategorias);

        btnConfirmar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aplicacao/imagens/icones/accept.png"))); // NOI18N
        btnConfirmar.setText("Confirmar");
        btnConfirmar.setEnabled(false);
        btnConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aplicacao/imagens/icones/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setEnabled(false);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jtfNome.setFont(new java.awt.Font("Arial", 0, 12));
        jtfNome.setEnabled(false);

        jtfNumRounds.setFont(new java.awt.Font("Arial", 0, 12));
        jtfNumRounds.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfNumRounds.setEnabled(false);

        cmbSexo.setFont(new java.awt.Font("Arial", 0, 12));
        cmbSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Masculino", "Feminino" }));
        cmbSexo.setEnabled(false);

        jpPeso.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Peso", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N

        jtfPesoMinimo.setFont(new java.awt.Font("Arial", 0, 12));
        jtfPesoMinimo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfPesoMinimo.setText("000");
        jtfPesoMinimo.setEnabled(false);

        jLabel6.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel6.setText("De ");

        jLabel7.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel7.setText(" até ");

        jtfPesoMaximo.setFont(new java.awt.Font("Arial", 0, 12));
        jtfPesoMaximo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfPesoMaximo.setText("000");
        jtfPesoMaximo.setEnabled(false);

        javax.swing.GroupLayout jpPesoLayout = new javax.swing.GroupLayout(jpPeso);
        jpPeso.setLayout(jpPesoLayout);
        jpPesoLayout.setHorizontalGroup(
            jpPesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpPesoLayout.createSequentialGroup()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfPesoMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfPesoMaximo, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
        );
        jpPesoLayout.setVerticalGroup(
            jpPesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpPesoLayout.createSequentialGroup()
                .addGroup(jpPesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jtfPesoMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(jtfPesoMaximo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jpIdade.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Idade", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N

        jLabel8.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel8.setText("De ");

        jLabel9.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel9.setText(" até ");

        jtfIdadeMinima.setFont(new java.awt.Font("Arial", 0, 12));
        jtfIdadeMinima.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfIdadeMinima.setText("000");
        jtfIdadeMinima.setEnabled(false);

        jtfIdadeMaxima.setFont(new java.awt.Font("Arial", 0, 12));
        jtfIdadeMaxima.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfIdadeMaxima.setText("000");
        jtfIdadeMaxima.setEnabled(false);

        javax.swing.GroupLayout jpIdadeLayout = new javax.swing.GroupLayout(jpIdade);
        jpIdade.setLayout(jpIdadeLayout);
        jpIdadeLayout.setHorizontalGroup(
            jpIdadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpIdadeLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfIdadeMinima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfIdadeMaxima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpIdadeLayout.setVerticalGroup(
            jpIdadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpIdadeLayout.createSequentialGroup()
                .addGroup(jpIdadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jtfIdadeMinima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(jtfIdadeMaxima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jpGraduacao.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Graduação", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N

        jLabel12.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel12.setText("De ");

        jLabel13.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel13.setText(" até ");

        jtfGraduacaoMinima.setFont(new java.awt.Font("Arial", 0, 12));
        jtfGraduacaoMinima.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfGraduacaoMinima.setText("000");
        jtfGraduacaoMinima.setEnabled(false);

        cmbGubMinimo.setFont(new java.awt.Font("Arial", 0, 12));
        cmbGubMinimo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gub", "Dan" }));
        cmbGubMinimo.setEnabled(false);

        jtfGraduacaoMaxima.setFont(new java.awt.Font("Arial", 0, 12));
        jtfGraduacaoMaxima.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfGraduacaoMaxima.setText("000");
        jtfGraduacaoMaxima.setEnabled(false);

        cmbGubMaximo.setFont(new java.awt.Font("Arial", 0, 12));
        cmbGubMaximo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gub", "Dan" }));
        cmbGubMaximo.setEnabled(false);

        javax.swing.GroupLayout jpGraduacaoLayout = new javax.swing.GroupLayout(jpGraduacao);
        jpGraduacao.setLayout(jpGraduacaoLayout);
        jpGraduacaoLayout.setHorizontalGroup(
            jpGraduacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpGraduacaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel12)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfGraduacaoMinima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbGubMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfGraduacaoMaxima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbGubMaximo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpGraduacaoLayout.setVerticalGroup(
            jpGraduacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpGraduacaoLayout.createSequentialGroup()
                .addGroup(jpGraduacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(jtfGraduacaoMinima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbGubMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13)
                    .addComponent(jtfGraduacaoMaxima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbGubMaximo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel1.setText("Sexo");

        jLabel2.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel2.setText("Nome");

        jLabel3.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel3.setText("Nº de Rounds");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtfNome, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(5, 5, 5)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtfNumRounds, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(cmbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jpPeso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpIdade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpGraduacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtfNumRounds, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpPeso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpIdade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpGraduacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jmIncluir.setText("Incluir");
        jmIncluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jmIncluirMousePressed(evt);
            }
        });
        jmbCategorias1.add(jmIncluir);

        jmAlterar.setText("Alterar");
        jmAlterar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jmAlterarMousePressed(evt);
            }
        });
        jmbCategorias1.add(jmAlterar);

        jmExcluir.setText("Excluir");
        jmExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jmExcluirMousePressed(evt);
            }
        });
        jmbCategorias1.add(jmExcluir);

        jmProcurar.setText("Procurar");
        jmProcurar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jmProcurarMousePressed(evt);
            }
        });
        jmbCategorias1.add(jmProcurar);

        jmSair.setText("Sair");
        jmSair.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jmSairMousePressed(evt);
            }
        });
        jmbCategorias1.add(jmSair);

        setJMenuBar(jmbCategorias1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnConfirmar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancelar))
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnConfirmar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jmSairMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmSairMousePressed
        if(modoAtual != 0)
            return;
        
        this.dispose();        
    }//GEN-LAST:event_jmSairMousePressed

    private void jmProcurarMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmProcurarMousePressed
        
        // Só permite se estiver em modo de navegação
        if(modoAtual!=0)
            return;
        
        String consulta = JOptionPane.showInputDialog(this, "Digite o nome " +
                "da categoria: ", "Consulta pelo nome da categoria", 
                JOptionPane.QUESTION_MESSAGE);

        // Se cancelou retorna
        if(consulta == null)
            return;
        
        // Se não digitou nada retorna
        if(consulta.trim().equals(""))
            return;
        
        ArrayList<Categoria> categorias = null;
        
        try {
            categorias = Categoria.listCategoriasPorNome(consulta);
        } catch (DAOException ex) {
            JOptionPane.showMessageDialog(this, "Problemas com o banco de "+
                    "dados", "Erro", JOptionPane.ERROR_MESSAGE);
            return; 
        } catch (CategoriaDadoIncorretoException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Erro",
                    JOptionPane.ERROR_MESSAGE);
            return; 
        }
        
        if(categorias.size() > 0) 
            new GuiResultadoBusca( this, true, new TableModelCategoria(
                    categorias), this, larguraColunas, false);
        else 
            JOptionPane.showMessageDialog(this, "Nenhuma categoria encontrada",
                    "Erro", JOptionPane.ERROR_MESSAGE);

    }//GEN-LAST:event_jmProcurarMousePressed

    private void jmExcluirMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmExcluirMousePressed
        
        /* Se não estiver no modo de navegação ou se o lutador ativo for
         *nulo, não permite a exclusão
         */
        if(modoAtual!=0 || this.getCategoriaAtiva() == null)
            return;
        
        Object[] options = { "NÃO", "SIM" };
        int opcao;
        
        // 0 = não, 1 = sim
        opcao = JOptionPane.showOptionDialog(null,
                "deseja remover este lutador?", "Atenção",
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                null, options, options[0]);
        
        if (opcao==1){
            try {
                this.getCategoriaAtiva().delete();
                
            } catch (DAOException ex) {
                JOptionPane.showMessageDialog(this, "Problemas com o banco de "+
                        "dados", "Erro", JOptionPane.ERROR_MESSAGE);
                return;       
            } finally {
                modoAtual = 0;
                ajustaControles();
                limpaCampos();
            }
            
        }
    }//GEN-LAST:event_jmExcluirMousePressed

    private void jmAlterarMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmAlterarMousePressed

        if(modoAtual!=0 || this.getCategoriaAtiva() == null)
            return;
        
        // Alteração
        modoAtual = 2;
        
        preencheCampos();
        
        ajustaControles();
    }//GEN-LAST:event_jmAlterarMousePressed

    private void jmIncluirMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmIncluirMousePressed

        if(modoAtual!=0)
            return;
        
        // Trocando modo atual para inclusão
        modoAtual = 1;

        this.limpaCampos();

        this.ajustaControles();
        
    }//GEN-LAST:event_jmIncluirMousePressed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        modoAtual = 0;
        
        this.limpaCampos();
        this.ajustaControles();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarActionPerformed

        int graduacaoMinima = Integer.parseInt( jtfGraduacaoMinima.getText()) *
                (cmbGubMinimo.getSelectedItem().equals("Gub") ? 1:-1);

        int graduacaoMaxima = Integer.parseInt( jtfGraduacaoMaxima.getText()) *
                (cmbGubMaximo.getSelectedItem().equals("Gub") ? 1:-1);        
        
        switch (modoAtual) {
            
            case 1:

                 break;
                 
            case 2:
                
                try {
                    this.getCategoriaAtiva().setNome(jtfNome.getText());                    
                    this.getCategoriaAtiva().setPesoMinimo(
                            Double.parseDouble(jtfPesoMinimo.getText()));
                    this.getCategoriaAtiva().setPesoMaximo(
                            Double.parseDouble(jtfPesoMaximo.getText()));
                    this.getCategoriaAtiva().setIdadeMinima(
                            Integer.parseInt(jtfIdadeMinima.getText()));
                    this.getCategoriaAtiva().setIdadeMaxima(
                            Integer.parseInt(jtfIdadeMaxima.getText()));
                    this.getCategoriaAtiva().setGraduacaoMinima(
                            graduacaoMinima);
                    this.getCategoriaAtiva().setGraduacaoMaxima(
                            graduacaoMaxima);
                    this.getCategoriaAtiva().setSexo(
                            (String) cmbSexo.getSelectedItem());
                    
                    this.getCategoriaAtiva().update();
                    
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(this, "Os dados não podem " +
                            "estar em branco", "Erro", 
                            JOptionPane.ERROR_MESSAGE);
                    util.Util.gravaExcecao(ex, this);
                    return;
                } catch (CategoriaDadoIncorretoException ex) {
                    JOptionPane.showMessageDialog(this, ex.getMessage(), "Erro", 
                            JOptionPane.ERROR_MESSAGE);
                    return;
                } catch (DAOException ex) {
                    JOptionPane.showMessageDialog(this, ex.getMessage(),
                            "Erro", JOptionPane.ERROR_MESSAGE);
                    return;                      
                } finally {
                    modoAtual = 0;
                    ajustaControles();
                    limpaCampos();

                }
                
                break;
            
        }
        
        
    }//GEN-LAST:event_btnConfirmarActionPerformed

    private void limpaCampos() {

       jtfNome.setText("");
       cmbSexo.setSelectedIndex(0);
       jtfPesoMinimo.setText("");
       jtfPesoMaximo.setText("");
       jtfIdadeMinima.setText("");
       jtfIdadeMaxima.setText("");
       jtfGraduacaoMinima.setText("");
       jtfGraduacaoMaxima.setText("");
       cmbGubMinimo.setSelectedIndex(0);
       cmbGubMaximo.setSelectedIndex(0);
        
    }
    
    private void ajustaControles() {
        
        boolean habilitado = false;
        
        switch (modoAtual) {
            
            case 0:
                habilitado = false;
                break;
                
            default:
                habilitado = true;
                break;                        
            
        }
        
       jtfNome.setEnabled(habilitado);
       jtfNumRounds.setEnabled(habilitado);
       cmbSexo.setEnabled(habilitado);
       jtfPesoMinimo.setEnabled(habilitado);
       jtfPesoMaximo.setEnabled(habilitado);
       jtfIdadeMinima.setEnabled(habilitado);
       jtfIdadeMaxima.setEnabled(habilitado);
       jtfGraduacaoMinima.setEnabled(habilitado);
       jtfGraduacaoMaxima.setEnabled(habilitado);
       cmbGubMinimo.setEnabled(habilitado);
       cmbGubMaximo.setEnabled(habilitado);
       
       btnConfirmar.setEnabled(habilitado);
       btnCancelar.setEnabled(habilitado);
       
       jTableCategorias.setEnabled(!habilitado);
        
    }
    
    private void preencheCampos(Categoria categoria) {

        if(categoria == null)
            return;
        
        jtfNome.setText(categoria.getNome());
        
        // Setando o sexo no combo
        if(categoria.getSexo().equalsIgnoreCase("M")){
            cmbSexo.setSelectedIndex(0);
        } else {
            cmbSexo.setSelectedIndex(1);
        }        
        
        jtfPesoMinimo.setText(""+categoria.getPesoMinimo());
        jtfPesoMaximo.setText(""+categoria.getPesoMaximo());
        jtfIdadeMinima.setText(""+categoria.getIdadeMinima());
        jtfIdadeMaxima.setText(""+categoria.getIdadeMaxima());
        jtfGraduacaoMinima.setText(""+
                Math.abs(categoria.getGraduacaoMinima()));
        jtfGraduacaoMaxima.setText(""+
                Math.abs(categoria.getGraduacaoMaxima()));        
        jtfNumRounds.setText(""+categoria.getNumRounds());
        
        // Setando se é GUB ou DAN nos combos
        if(categoria.getGraduacaoMinima() > 0){
            cmbGubMinimo.setSelectedIndex(0);
        } else {
            cmbGubMinimo.setSelectedIndex(1);
        }

        if(categoria.getGraduacaoMaxima() > 0){
            cmbGubMaximo.setSelectedIndex(0);
        } else {
            cmbGubMaximo.setSelectedIndex(1);
        }        
    }
    
    private void preencheCampos(){

        preencheCampos(this.getCategoriaAtiva());        
        
    }
    
    private Categoria getCategoriaAtiva() {

        return ( (TableModelCategoria) 
            jTableCategorias.getModel()).getCategoria(
                jTableCategorias.getSelectedRow());
        
    }

    public void focusGained(FocusEvent e) {
        
        if (modoAtual != 0)
            return;
        
        preencheCampos();  
        
    }

    public void focusLost(FocusEvent e) {

        if (modoAtual != 0)
            return;
        
        preencheCampos();  
    
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
        if (modoAtual != 0)
            return;
        
        preencheCampos();          
    }

    public void keyReleased(KeyEvent e) {
    }

    public void mouseClicked(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
        if (modoAtual != 0)
            return;
        
        preencheCampos();          
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void setResultadoBusca(Object o) {
        
        if(o instanceof Categoria)
            this.preencheCampos((Categoria) o);
        
    }
       
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JComboBox cmbGubMaximo;
    private javax.swing.JComboBox cmbGubMinimo;
    private javax.swing.JComboBox cmbSexo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JTable jTableCategorias;
    private javax.swing.JMenu jmAlterar;
    private javax.swing.JMenu jmExcluir;
    private javax.swing.JMenu jmIncluir;
    private javax.swing.JMenu jmProcurar;
    private javax.swing.JMenu jmSair;
    private javax.swing.JMenuBar jmbCategorias1;
    private javax.swing.JPanel jpGraduacao;
    private javax.swing.JPanel jpIdade;
    private javax.swing.JPanel jpPeso;
    private javax.swing.JTextField jtfGraduacaoMaxima;
    private javax.swing.JTextField jtfGraduacaoMinima;
    private javax.swing.JTextField jtfIdadeMaxima;
    private javax.swing.JTextField jtfIdadeMinima;
    private javax.swing.JTextField jtfNome;
    private javax.swing.JTextField jtfNumRounds;
    private javax.swing.JTextField jtfPesoMaximo;
    private javax.swing.JTextField jtfPesoMinimo;
    // End of variables declaration//GEN-END:variables
    
}
